package mamikeji.liaowa.ui.activity.diary;

import android.app.Dialog;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import mamikeji.liaowa.R;
import mamikeji.liaowa.bean.DiaryEveryDayBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.BaseActivity;
import mamikeji.liaowa.ui.adapter.DiaryListExpandableListAdapter;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;
import mamikeji.liaowa.widget.floatingactionbutton.FloatingActionButton;
import mamikeji.liaowa.widget.pulltorefresh.PullToRefreshBase;
import mamikeji.liaowa.widget.pulltorefresh.PullToRefreshExpandableListView;
import mamikeji.liaowa.widget.refreshView.PtrlDownRefreshFrameLayout;

public class EveryDayDiaryActivity extends BaseActivity {
    private static final String TAG = "EveryDayDiaryActivity";
    private static final int TAG_CIRCLE = 1001;
    private PullToRefreshExpandableListView expandableListView_diary_evetyday;
    private PtrlDownRefreshFrameLayout ptrlDownRefreshFrameLayout_diary_evetyday;
    private DiaryListExpandableListAdapter diaryListExpandableListAdapter;
    private List<DiaryEveryDayBean.DataEntity> dataBeanList = new ArrayList<>();
    private List<DiaryEveryDayBean.DataEntity> mList;
    private FloatingActionButton multiple_actions_every_day_diary;

    private MultiStateView multiStateView_diary_evetyday;

    private Dialog dialog_share, dialog_share_query, dialog_delete;

    private int positions, groupPositions, childPositions, diary_id;

    /**
     * 请求的页数
     */
    private int page = 1;
    /**
     * 总页数
     */
    private int maxPage = 0;

    private Boolean bool_delte = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_every_day_diary);
        getBase();
        setTitleLeftBtn();
        setTitleName(R.string.everyday_diary_name);
        setTitleRightImage(R.drawable.icon_shanchunaozhong_n, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (bool_delte){
                    /**震动服务*/
                    Vibrator vib = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
                    vib.vibrate(50);//只震动一秒，一次

                    diaryListExpandableListAdapter.bool_delete = !diaryListExpandableListAdapter.bool_delete;
                    diaryListExpandableListAdapter.getDelete();
                }
            }
        });

        init();
        initDate(1, 10);
        getDialogShare();
        getDigLog();
        showDeleteDialog();

        expandableListView_diary_evetyday.getRefreshableView().expandGroup(0);
    }

    private void init() {
        multiple_actions_every_day_diary = (FloatingActionButton) findViewById(R.id.multiple_actions_every_day_diary);
        ptrlDownRefreshFrameLayout_diary_evetyday = (PtrlDownRefreshFrameLayout) findViewById(R.id.ptrlDownRefreshFrameLayout_diary_evetyday);
        expandableListView_diary_evetyday = (PullToRefreshExpandableListView) findViewById(R.id.expandableListView_diary_evetyday);

        multiStateView_diary_evetyday = (MultiStateView) findViewById(R.id.multiStateView_diary_evetyday);

        multiStateView_diary_evetyday.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.button_error_refish)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiStateView_diary_evetyday.setViewState(MultiStateView.VIEW_STATE_LOADING);
                        initDate(1, 10);
                    }
                });

        multiStateView_diary_evetyday.setEmptyText(R.string.user_diary_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityForResult(new Intent(EveryDayDiaryActivity.this, PublishDiaryActivity.class),TAG_CIRCLE);
            }
        });

        diaryListExpandableListAdapter = new DiaryListExpandableListAdapter(EveryDayDiaryActivity.this, dataBeanList);
        expandableListView_diary_evetyday.getRefreshableView().setAdapter(diaryListExpandableListAdapter);

        diaryListExpandableListAdapter.setOnItemClickListener(new DiaryListExpandableListAdapter.OnItemClickListener() {
            @Override
            public void onShareClick(int position, int groupPosition, int childPosition) {
                MobclickAgent.onEvent(EveryDayDiaryActivity.this,"DailyDiaryShare");//每日日记-分享
                EveryDayDiaryActivity.this.positions = position;
                EveryDayDiaryActivity.this.groupPositions = groupPosition;
                EveryDayDiaryActivity.this.childPositions = childPosition;
                dialog_share.show();
            }

            @Override
            public void onDeleteClick(int diary_id, int position, int groupPosition, int childPosition) {
                EveryDayDiaryActivity.this.diary_id = diary_id;
                EveryDayDiaryActivity.this.positions = position;
                EveryDayDiaryActivity.this.groupPositions = groupPosition;
                EveryDayDiaryActivity.this.childPositions = childPosition;
                dialog_delete.show();
            }
        });

        ptrlDownRefreshFrameLayout_diary_evetyday.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, expandableListView_diary_evetyday.getRefreshableView(), header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                initDate(1, 10);
            }
        });
        expandableListView_diary_evetyday.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        expandableListView_diary_evetyday.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ExpandableListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ExpandableListView> refreshView) {

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ExpandableListView> refreshView) {
                initDate(++page, 10);
            }
        });
        multiple_actions_every_day_diary.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityForResult(new Intent(EveryDayDiaryActivity.this, PublishDiaryActivity.class),TAG_CIRCLE);
            }
        });

        expandableListView_diary_evetyday.getRefreshableView().setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
                return false;
            }
        });
    }

    private void initDate(final int indexpage, int pagesize) {
        Map<String, String> formMap = new HashMap<>();
        formMap.put(HttpKey.ESSAY_EVERYDAY_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.ESSAY_EVERYDAY_PAGE, indexpage + "");
        formMap.put(HttpKey.ESSAY_EVERYDAY_PAGESIZE, pagesize + "");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.ESSAY_EVERYDAY, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                multiStateView_diary_evetyday.setViewState(MultiStateView.VIEW_STATE_NOINTERNET);
                ptrlDownRefreshFrameLayout_diary_evetyday.refreshComplete();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                expandableListView_diary_evetyday.onRefreshComplete();
                ptrlDownRefreshFrameLayout_diary_evetyday.refreshComplete();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        DiaryEveryDayBean diaryEveryDayBean = new Gson().fromJson(response, DiaryEveryDayBean.class);
                        if (diaryEveryDayBean.getData() != null && diaryEveryDayBean.getData().size() > 0) {
                            mList = new ArrayList<DiaryEveryDayBean.DataEntity>();
                            mList = diaryEveryDayBean.getData();

                            if (mList.size() <= 0) {
                                new Handler().postDelayed(new Runnable() {
                                    public void run() {
                                        expandableListView_diary_evetyday.onRefreshComplete();
                                    }
                                }, 1000);
                                ForToast.showToast(R.string.error_down_end);
                            } else {
                                if (indexpage == 1) {
                                    bool_delte = true;
                                    dataBeanList.clear();
                                    dataBeanList.addAll(diaryEveryDayBean.getData());
                                    diaryListExpandableListAdapter.notifyDataSetChanged();
                                } else {
                                    dataBeanList.addAll(mList);
                                    diaryListExpandableListAdapter.notifyDataSetChanged();
                                }
                            }
                            multiStateView_diary_evetyday.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        } else {
                            if (indexpage == 1)
                                multiStateView_diary_evetyday.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                        }
                    } else {
                        multiStateView_diary_evetyday.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 确认删除
     */
    private RelativeLayout relativeLayout_clock_dig_query, relativeLayout_clock_dig_btnerror;

    private void showDeleteDialog() {
        dialog_delete = new Dialog(EveryDayDiaryActivity.this, R.style.DialogLoading);
        View inflate = LayoutInflater.from(EveryDayDiaryActivity.this).inflate(R.layout.diglog_clock_delete, null);
        dialog_delete.setContentView(inflate);

        relativeLayout_clock_dig_query = (RelativeLayout) inflate.findViewById(R.id.relativeLayout_clock_dig_query);
        relativeLayout_clock_dig_btnerror = (RelativeLayout) inflate.findViewById(R.id.relativeLayout_clock_dig_btnerror);

        relativeLayout_clock_dig_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog_delete.hide();

                getDelete_DiaryData();
            }
        });
        relativeLayout_clock_dig_btnerror.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog_delete.hide();
            }
        });
    }

    /**
     * 删除每日随笔
     */
    private void getDelete_DiaryData() {
        showLoading();
        //参数集合
        Map<String, String> formMap = new HashMap<>();
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.ESSAY_DELETE_DATE
                + "?" + HttpKey.ESSAY_DELETE_ID + "=" + EveryDayDiaryActivity.this.diary_id, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                hideLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        ForToast.showToast("已删除！");

                        int num = ForPreference.getInt(ForContents.USER_every_diary) - 1;
                        ForPreference.putInt(ForContents.USER_every_diary, num);
                        
                        dataBeanList.get(EveryDayDiaryActivity.this.groupPositions)
                                .getList()
                                .remove(EveryDayDiaryActivity.this.positions);
                        diaryListExpandableListAdapter.notifyDataSetChanged();

                        if (dataBeanList.size() <= 0) {
                            multiStateView_diary_evetyday.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                        }
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 分享弹框
     */
    public void getDialogShare() {
        dialog_share = new Dialog(this, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(this).inflate(R.layout.diglog_set_shape, null);
        dialog_share.setContentView(view);
        Window dialogWindow = dialog_share.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 0;
        lp.width = getResources().getDisplayMetrics().widthPixels; // 宽度
        dialogWindow.setAttributes(lp);

        RelativeLayout relativeLayout_share_liaowa = (RelativeLayout) view.findViewById(R.id.relativeLayout_share_liaowa);
        relativeLayout_share_liaowa.setVisibility(View.VISIBLE);
        LinearLayout linearLayout_share_liaowa = (LinearLayout) view.findViewById(R.id.linearLayout_share_liaowa);

        LinearLayout linearLayout_share_wechatFriend = (LinearLayout) view.findViewById(R.id.linearLayout_share_wechatFriend);
        LinearLayout linearLayout_share_wechatCircle = (LinearLayout) view.findViewById(R.id.linearLayout_share_wechatCircle);
        LinearLayout linearLayout_share_tencentCircle = (LinearLayout) view.findViewById(R.id.linearLayout_share_tencentCircle);

        linearLayout_share_wechatFriend.setVisibility(View.GONE);
        linearLayout_share_wechatCircle.setVisibility(View.GONE);
        linearLayout_share_tencentCircle.setVisibility(View.GONE);

        linearLayout_share_liaowa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog_share.hide();
                dialog_share_query.show();
            }
        });
//        linearLayout_share_wechatFriend.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                dialog_share.hide();
//                ShareWeb(SHARE_MEDIA.WEIXIN);
//            }
//        });
//        linearLayout_share_wechatCircle.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                dialog_share.hide();
//                ShareWeb(SHARE_MEDIA.WEIXIN_CIRCLE);
//            }
//        });
//        linearLayout_share_tencentCircle.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                dialog_share.hide();
//                ShareWeb(SHARE_MEDIA.QZONE);
//            }
//        });
    }

    private TextView textView_dig_cache_text;
    private RelativeLayout relativeLayout_set_dig_btnerror, relativeLayout_set_dig_query;

    private void getDigLog() {
        dialog_share_query = new Dialog(EveryDayDiaryActivity.this, R.style.DialogLoading);
        View inflate = LayoutInflater.from(EveryDayDiaryActivity.this).inflate(R.layout.diglog_set_clearcache, null);
        dialog_share_query.setContentView(inflate);

        textView_dig_cache_text = (TextView) inflate.findViewById(R.id.textView_dig_cache_text);
        relativeLayout_set_dig_btnerror = (RelativeLayout) inflate.findViewById(R.id.relativeLayout_set_dig_btnerror);
        relativeLayout_set_dig_query = (RelativeLayout) inflate.findViewById(R.id.relativeLayout_set_dig_query);

        textView_dig_cache_text.setText("是否分享到妈蜜圈？");

        relativeLayout_set_dig_btnerror.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog_share_query.hide();
            }
        });
        relativeLayout_set_dig_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog_share_query.hide();
                if (dataBeanList.get(groupPositions).getList().get(positions).getImages().size() > 0) {
                    StringBuffer imagePath = new StringBuffer();
                    for (int i = 0; i < dataBeanList.get(groupPositions).getList().get(positions).getImages().size(); i++) {
                        if (i == dataBeanList.get(groupPositions).getList().get(positions).getImages().size() - 1) {
                            imagePath.append(dataBeanList.get(groupPositions).getList().get(positions).getImages().get(i));
                        } else {
                            imagePath.append(dataBeanList.get(groupPositions).getList().get(positions).getImages().get(i) + ",");
                        }
                    }
                    if (dataBeanList.get(groupPositions).getList().get(positions).getContent().equals("") ||
                            dataBeanList.get(groupPositions).getList().get(positions).getContent() == null) {
                        publicCircle("", imagePath.toString(), "2");
                    } else {
                        publicCircle(dataBeanList.get(groupPositions).getList().get(positions).getContent(), imagePath.toString(), "3");
                    }
                } else {
                    publicCircle(dataBeanList.get(groupPositions).getList().get(positions).getContent(), "", "1");
                }
            }
        });
    }

    private void publicCircle(String content, String imagePath, String type) {
        showLoading();
        Map<String, String> formMap = new HashMap<>();
        formMap.put("fc_UserId", ForPreference.getString(ForContents.USER_CODE));
        formMap.put("fc_Titile", content);
        formMap.put("fc_Titile", content);
        formMap.put("fc_Content", content);
        formMap.put("fc_ContentType", type);//朋友圈内容类型 1文字 2图片 3图品文字 ,
        formMap.put("fc_ImageUrl", imagePath);
        formMap.put("fc_Type", "1");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.PUBLIC_CIRCLE, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForToast.showToast(R.string.intent_error);
                hideLoading();
                ForPreference.putBoolean(ForContents.DIARY_SHARE_BOOL, false);
            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        ForToast.showToast("分享成功");
                        ForPreference.putBoolean(ForContents.DIARY_SHARE_BOOL, true);
                        finish();
                    } else {
                        ForPreference.putBoolean(ForContents.DIARY_SHARE_BOOL, false);
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                    hideLoading();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 分享回调
     *
     * @param anEnum
     */
    private void ShareWeb(Enum anEnum) {
        ForLog.i("EveryDayDiaryActivityEveryDayDiaryActivity",
                "diary_id："+diary_id +
                        "    positions："+positions+
                        "    groupPositions："+groupPositions+
                        "    childPositions："+childPositions);
        List<String> urls = dataBeanList.get(groupPositions).getList().get(positions).getImages();
        UMImage thumb;
        if (urls.size() > 0){
            if (urls.size() == 1){
                if (urls.get(0).equals("") || urls.get(0).equals("null") || urls.get(0).equals(" ")){
                    thumb = new UMImage(this, R.mipmap.ic_launcher);
                }else {
                    thumb = new UMImage(this, urls.get(0)+"?x-oss-process=image/resize,w_220");
                }
            }else {
                thumb = new UMImage(this, urls.get(0)+"?x-oss-process=image/resize,w_220");
            }
        }else {
            thumb = new UMImage(this, R.mipmap.ic_launcher);
        }
        UMWeb web = new UMWeb(HttpApi.DIARY_SHARE + dataBeanList.get(groupPositions).getList().get(positions).getId());
        web.setThumb(thumb);
        web.setDescription(dataBeanList.get(groupPositions).getList().get(positions).getContent());
        web.setTitle(ForPreference.getString(ForContents.USER_NAME)+"的动态");
        new ShareAction(this).withMedia(web).setPlatform((SHARE_MEDIA) anEnum).setCallback(new UMShareListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
                ForToast.showToast("后台正在玩儿命加载~~~");
            }

            @Override
            public void onResult(SHARE_MEDIA share_media) {
                ForToast.showToast("分享成功！");
            }

            @Override
            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                ForToast.showToast("分享失败！");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {
                ForToast.showToast("取消分享！");
            }
        }).share();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            if (requestCode == TAG_CIRCLE) {
                //获取每日随笔
                initDate(1, 10);
                expandableListView_diary_evetyday.getRefreshableView().expandGroup(0);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("每日日记");
        MobclickAgent.onResume(this);       //开始统计时长
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("每日日记");
        MobclickAgent.onPause(this);       //结束统计时长
    }
}
